const { Service } = require('egg')
const { encodeInp } = require('../utils/encryption')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      const encoded = `${encodeInp(sid)}%%%${encodeInp(pwd)}Lg==`
      console.log('encoded', encoded)
      const apiUrl = `${ctx.state.baseUrl}/znlykjdxswxy_jsxsd/xk/LoginToXk`
      console.log('apiUrl', apiUrl)
      const res = await ctx.curl(apiUrl, {
        method: 'POST',
        data: {
          encoded,
        },
        headers: {
          // Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        timeout: 10000,
      })
      console.log('res', res)
      const setCookie = res.headers['set-cookie'] ? res.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      return { setCookie, status: res.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
